package com.hao.demo.grpc.consumer.controller;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.hao.demo.grpc.api.*;
import io.grpc.stub.StreamObserver;
import net.devh.boot.grpc.client.inject.GrpcClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/demo")
public class DemoController {

    @GrpcClient("demoServer")
    private DemoServiceGrpc.DemoServiceBlockingStub blockingStub;
    @GrpcClient("demoServer")
    private DemoServiceGrpc.DemoServiceFutureStub futureStub;

    @GetMapping("/get")
    public String get(@RequestParam("id") Integer id) {
        long s = System.currentTimeMillis();

        // 创建请求
        DemoGetRequest request = DemoGetRequest.newBuilder().setId(id).build();
        // 执行 gRPC 请求 同步
        DemoGetResponse response = blockingStub.get(request);
        // future
        /*ListenableFuture<DemoGetResponse> future = futureStub.get(request);
        DemoGetResponse response = null;
        try {
            response = future.get(5, TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
        }*/

        long e = System.currentTimeMillis();
        long l = e - s;
        System.out.println("毫秒：" + l + ", 秒：" + (l / 1000));

        // 响应
        return response.getName();
    }

    @GetMapping("/create") // 为了方便测试，实际使用 @PostMapping
    public Integer create(@RequestParam("name") String name,
                          @RequestParam("gender") Integer gender) {
        long s = System.currentTimeMillis();

        // 创建请求
        DemoCreateRequest request = DemoCreateRequest.newBuilder()
                .setName(name)
                .setGender(gender)
                .build();
        // 执行 gRPC 请求 同步
        DemoCreateResponse response = blockingStub.create(request);

        long e = System.currentTimeMillis();
        long l = e - s;
        System.out.println("毫秒：" + l + ", 秒：" + (l / 1000));

        // 响应
        return response.getId();
    }

}
